package com.ocom.mqsubsidy.business.coupons;

import com.alibaba.fastjson.JSON;
import com.ocom.common.vo.webapi.ExcelCouponsVoucherListVo;
import com.ocom.mqsubsidy.config.ImportCouponsVoucherConfig;
import com.ocom.mqsubsidy.feign.PayConfigClientService;
import com.ocom.redis.util.RedisUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Map;


@Component
public class ImportCouponsVoucherMqListener {

	private Logger logger = LoggerFactory.getLogger(ImportCouponsVoucherMqListener.class);

	@Resource
	private PayConfigClientService payConfigClientService;

	@Resource
	private RedisUtil redisUtil;


	/**
	 * 把该监听命名为A监听
	 * 监听队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues = ImportCouponsVoucherConfig.IMPORT_COUPONS_QUEUE)
	public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		logger.info("ImportCoupons 消费中");
		logger.info("message【{}】",message);
		String humanMessage = new String(message.getBody(), StandardCharsets.UTF_8);
		//TODO 数据库操作样例
		logger.info("ImportCoupons-start:【{}】",humanMessage);
		logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());

		Object requestRedis =  redisUtil.get(humanMessage);

		try {
			ExcelCouponsVoucherListVo excelAddCouponsVo = JSON.parseObject(JSON.toJSONString(requestRedis),ExcelCouponsVoucherListVo.class);
			payConfigClientService.importCouponsVoucher(excelAddCouponsVo);
		} catch (Exception e) {
			logger.info("ImportCoupons-出现异常队列消息开始进入死信队列{{}}",e);
		}

		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		logger.info("ImportCoupons-end:【{}】",humanMessage);
		logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());
	}

	/**
	 * 把该监听命名为B监听
	 * 监听死信队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues =  ImportCouponsVoucherConfig.IMPORT_COUPONS_DIE_QUEUE)
	public void processForDie(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		//死信队列放弃
		channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
		logger.info("导入人员-死信队列放弃 ， 【{}】",message);
	}


}
